package com.hyperzsoft.budget;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hyperzsoft.budget.DBProvider.BudgetTable;
import com.hyperzsoft.budget.DBProvider.Expense;

public class ExpenseList extends ListActivity {
	static private String TAG = "ExpenseList";
	
	private ArrayList<Expense> m_Expenses = null;
	private ProgressDialog m_ProgressDialog = null;
	private expenseListAdapter m_adapter;
	private Runnable viewExpenses;
	private DBProvider dbProvider;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.expense_list);
		dbProvider = new DBProvider(this);
		setupList();
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == getResources().getInteger(R.integer.request_code_edit_expense)
        		|| requestCode == getResources().getInteger(R.integer.request_code_new_expense)) {
            if (resultCode == RESULT_OK) {
            	setupList();
            } else if (resultCode == RESULT_CANCELED) {
            	//do nothing for now
            }
        }
    }
	
	private final Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			if(m_Expenses != null && m_Expenses.size() > 0){
				m_adapter.notifyDataSetChanged();
				for(int i=0;i<m_Expenses.size();i++)
					m_adapter.add(m_Expenses.get(i));
			}
			m_ProgressDialog.dismiss();
			m_adapter.notifyDataSetChanged();
		}
	};
	
	private void setupList() {
		m_Expenses = new ArrayList<Expense>();
		this.m_adapter = new expenseListAdapter(this, R.layout.expense_list_item, m_Expenses);
		setListAdapter(this.m_adapter);
		
		viewExpenses = new Runnable(){
			@Override
			public void run() {
				getExpenseList();
			}
		};
		
		Thread thread =  new Thread(null, viewExpenses, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(this,    
				"Please wait...", "Retrieving data ...", true);
		
		ListView lv = getListView();
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				m_adapter.setSelectedPosition(position);
			}
		});
		
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent myIntent = new Intent();
				
				m_adapter.setSelectedPosition(position);
				myIntent.putExtra("selected_expense_id", m_adapter.getSelectedIndexId());
				myIntent.setClassName("com.hyperzsoft.budget", "com.hyperzsoft.budget.ExpenseEdit");
				startActivityForResult(myIntent, getResources().getInteger(R.integer.request_code_edit_expense));
				return false;
			}
		});
	}
	
	private void getExpenseList(){
		ArrayList<Object> workingList;
		
		try{
			m_Expenses = new ArrayList<Expense>();
			dbProvider.open();
			workingList = dbProvider.selectAll(BudgetTable.EXPENSE, getApplicationContext().getString(R.string.expense_name) + " asc", null, null);
			dbProvider.close();
			
			for (Object obj : workingList){
				m_Expenses.add((Expense)obj);
			}
			
			workingList = null;
			
			Thread.sleep(500);
			Log.i("ARRAY", ""+ m_Expenses.size());
		} catch (Exception e) {
			Log.e(TAG + " @getExpenseList", e.getStackTrace().toString());
		}
		
		runOnUiThread(returnRes);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.expense_list_menu, menu);
			return true;
		} catch (Exception e) {
			Log.e(TAG, e.getStackTrace().toString());
			return false;
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent myIntent = new Intent();
		
		try {
			// Handle item selection
			switch (item.getItemId()) {
			case R.id.expense_type_add:
				myIntent.setClassName("com.hyperzsoft.budget", "com.hyperzsoft.budget.ExpenseEdit");
				startActivityForResult(myIntent, getResources().getInteger(R.integer.request_code_new_expense));
				return true;
			case R.id.expense_type_edit:
				myIntent.putExtra("selected_type_id", m_adapter.getSelectedIndexId());
				myIntent.setClassName("com.hyperzsoft.budget", "com.hyperzsoft.budget.ExpenseEdit");
				startActivityForResult(myIntent, getResources().getInteger(R.integer.request_code_edit_expense));
				return true;
			case R.id.expense_type_del:
				dbProvider.open();
				Expense expense = dbProvider.new Expense();
				expense._ID = m_adapter.getSelectedIndexId();
				expense.delete();
				dbProvider.close();
				setupList();
				return true;
			case R.id.back:
				finish();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		} catch (Exception e) {
			Log.e(TAG, e.toString());
			return false;
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle instanceState) {
		super.onSaveInstanceState(instanceState);
	}
	
	public void reload() {

	    Intent intent = getIntent();
	    overridePendingTransition(0, 0);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	    finish();

	    overridePendingTransition(0, 0);
	    startActivity(intent);
	}
	
	public class expenseListAdapter extends ArrayAdapter<Expense> {
		private int selectedPos = -1; 
		private final ArrayList<Expense> items;
		
		public expenseListAdapter(Context context, int textViewResourceId, ArrayList<Expense> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		public void setSelectedPosition(int pos){
			selectedPos = pos;
			// inform the view of this change
			notifyDataSetChanged();
		}

		public int getSelectedPosition(){
			return selectedPos;
		}
		
		public long getSelectedIndexId() {
			Expense expenses = items.get(selectedPos);
			
			return expenses._ID;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			NumberFormat f = NumberFormat.getCurrencyInstance();
			
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.expense_list_item, null);
			}
			
			LinearLayout ll = (LinearLayout)v.findViewById(R.id.expense_list_item);
			//TODO: no validation on View or Linear layout objects
			if(selectedPos == position){
				v.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_royal_blue)));
				ll.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_translucent_midnight_blue)));
			} else {
				v.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_translucent_black)));
				ll.setBackgroundColor(Color.parseColor(getApplicationContext().getString(R.color.list_item_translucent_black)));
			}
			
			Expense expenses = items.get(position);
			
			if (expenses != null) {
				TextView tt = (TextView) v.findViewById(R.id.expense_name);
				TextView bt = (TextView) v.findViewById(R.id.expense_amount);
				TextView id = (TextView) v.findViewById(R.id.expense_id);
				
 				if (tt != null) {
					tt.setText("Name: "+ expenses.NAME);   
					tt.setTextColor(expenses.EXPENSE_TYPE.COLOR);
				}
				if(bt != null){
					((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
					bt.setText("Amount: "+ ((DecimalFormat)f).format(expenses.AMOUNT));
					bt.setTextColor(expenses.EXPENSE_TYPE.COLOR);
				}
				if(id != null){
					id.setText(Long.toString(expenses._ID));
				}
			}
			
			return v;
		}
	}
}
